const { error_fun } = require('../app/constants/error-types');
const { API_message_500, API_message_200 } = require('../app/constants/messageAPI');
const md5password = require('../app/utils/password-handle');
const userService = require('../service/user.service');

// 注册 
const verifyUser = async (ctx, next) => {
    //获取用户名和密码
    const { username, password } = ctx.request.body;
    // console.log(username)

    //检查参数
    if (!username || !password || username === '' || password === '') {
        ctx.body = API_message_500("账号或密码不能为空");
        return error_fun(ctx, 'username_or_password_is_required')
    }

    //判断用户是否存在
    const result = await userService.getUserByName(username);
    if (result.length) {
        ctx.body = API_message_500("用户已存在");
        return error_fun(ctx, '用户已存在')
    }
    
    await next();
}

//加密手机号
const handlePassword = async (ctx, next) => {
    const { password } = ctx.request.body;

    ctx.request.body.password = md5password(password);

    if (ctx.request.body.password) {
        await next()
    } else {
        ctx.body = API_message_500("系统错误");
        return error_fun(ctx, '密码加密失败')
    }
}


module.exports = { verifyUser, handlePassword }